package net.gazhi.delonix.grac.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.gazhi.delonix.core.entity.LoginUser;
import net.gazhi.delonix.core.thread.ThreadContext;
import net.gazhi.delonix.grac.service.ActionAuthorizationService;
import net.gazhi.delonix.grac.web.controller.pub.ErrorPageController;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * Handler方法鉴权拦截器处理器<br>
 * 在调用方法之前，判断是否有调用该方法的权限
 */
public class ActionAuthorizationInterceptor extends HandlerInterceptorAdapter {

	private final static Log log = LogFactory.getLog(ActionAuthorizationInterceptor.class);

	@Autowired
	private ActionAuthorizationService actionAuthorizationService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		LoginUser loginUser = ThreadContext.getLoginUser();

		if (loginUser.getId() <= 0) {
			// 未登录
			request.getRequestDispatcher(ErrorPageController.PAGE_NO_LOGIN).forward(request, response);
			return false;
		} else if (!this.actionAuthorizationService.isAuthorized((HandlerMethod) handler)) {
			// 已登录，但无权访问
			log.warn("User " + loginUser.getLoginName() + " is denied to access " + request.getRequestURI());
			request.getRequestDispatcher(ErrorPageController.PAGE_ACTION_ACCESS_DEINED).forward(request, response);
			return false;
		}
		return true;
	}

}